import { login, logout, getUserInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
const state = {
    token: getToken(),
    name: sessionStorage.getItem('username') || '',
    userId: null,
    role: null
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token
        sessionStorage.setItem('token', token)
    },
    SET_NAME: (state, name) => {
        state.name = name
        sessionStorage.setItem('username', name)
    },
    SET_ROLE: (state, role) => {
        state.role = role
        sessionStorage.setItem('role', role)
    },
    SET_USER_ID: (state, userId) => {
        state.userId = userId
    }
}

const actions = {
    // user login
    login({ commit, dispatch }, userParams) {
        return new Promise(async(resolve, reject) => {
            const { data } = await login(userParams).catch((err) => {
                reject(error)
            })
            commit('SET_TOKEN', data.token)
            setToken(data.token)
            dispatch('_getUserInfo')
            resolve(true)
        })
    },
    async _getUserInfo({ commit }) {
        const { data } = await getUserInfo()
        const { id, role, realName } = data
        commit('SET_NAME', realName)
        commit('SET_ROLE', role)
        commit('SET_USER_ID', id)

        return data
    },
    // user logout
    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
            commit('SET_TOKEN', '')
            commit('SET_NAME', '')
            removeToken()
            resetRouter()
            resolve().catch((error) => {
                reject(error)
            })
        })
    },

    // remove token
    resetToken({ commit }) {
        return new Promise((resolve) => {
            commit('SET_TOKEN', '')
            removeToken()
            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}